<template>
  <div class="main">
    <span class="head">交叉分析</span><br><br>
    <el-card class="card" shadow="hover" >
      <el-collapse v-model="isActive">
        <el-collapse-item title="我的交叉分析" name="1">
          <div class="argument">
            <span class="title">自变量X</span>
            <span class="description">（一般为样本属性，例如年龄等）</span>
            <div v-for="selection in selections">
              <br>
              <el-select v-model="selection.value" placeholder="请选择自变量" clearable>
                <el-option v-for="(option) in questions"
                           :key="option.value"
                           :label="option.label"
                           :value="option.value"
                           :disabled="isShow(option)">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="dependency">
            <span class="title">自变量Y</span>
            <span class="description">(您要分析的目标题目，限5题)</span>
            <div v-for="(selection, index) in selections2">
              <br>
              <el-select v-model="selection.value" placeholder="请选择因变量" clearable>
                <el-option v-for="(option) in questions"
                           :key="option.value"
                           :label="option.label"
                           :value="option.value"
                           :disabled="isShow(option)" >
                </el-option>
              </el-select>
              <span>&nbsp;&nbsp;</span>
              <el-button
                  v-if="index === selections2.length - 1"
                  type="primary"
                  icon="el-icon-plus"
                  circle
                  @click="addArgument2">
              </el-button>
              <el-button
                  v-if="index === selections2.length - 1 && selections2.length !== 1"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteClick2">
              </el-button>

            </div>
          </div>
          <br><br>
          <div>
            <el-button @click="printClick" round>交叉分析</el-button>
          </div>
        </el-collapse-item>
      </el-collapse>

    </el-card>
    <br><br>
    <div v-for="(selection, index) in selections2">
      <div v-if="showGraph[index] === 'primary'">
        <span class="descriptionNumber">第{{selection.value}}题&ensp;&ensp;</span>
        <span class="descriptionTitle">{{getQuestionTitle(selection.value)}}&ensp;</span>
        <span class="descriptionType">[{{getQuestionType(selection.value)}}]</span>
      </div>
      <div v-if="showGraph[index] === 'primary'" class="graph" :id=graph_id[index]></div>
      <br><br>
      <el-divider style="width: 80%; border-top: 1px dashed rgba(64,158,243,0.3);"></el-divider>
    </div>
  </div>

</template>

<script>
import axios from 'axios'
import qs from 'qs'
import * as echarts from 'echarts'
import {v4 as uuidv4} from 'uuid'
export default {
  name: "Cross",
  data() {
    return {
      isActive: ['1'],
      selections: [{value: ''}],
      questions: [],
      selections2: [{value: ''}],
      showGraph: ['', '', '', '',''],
      graph_id:['', '','', '', '']
    }
  },
  created() {
    for(let i = 0; i < this.graph_id.length; i++){
      this.graph_id[i] = uuidv4()
    }
    console.log(this.graph_id);
    const data = {
      questionnaireId: this.$route.query.questionnaireId
    }
    axios.post('/api/questionnaire/getInfo', qs.stringify(data)).then((res) => {
      if(res.data.code === 0) {
        this.questions = res.data.data.questions
        let i = 1
        this.questions.forEach(question => {
          question.value = i++
          question.label = ''+question.value + '.'+question.title
        })
      } else this.$message.error(res.data.msg)
      this.questions = this.questions.filter(question => question.type !== 'completion')
    })
  },
  methods: {
    getQuestionTitle(value) {
      let title = ''
      this.questions.forEach(question => {
        if(question.value === value){
          title = question.title
        }
      })
      return title
    },
    getQuestionType(value) {
      let type = ''
      this.questions.forEach(question => {
        if(question.value === value){
          type = question.type
        }
      })
      switch (type) {
        case "radio": type = '单选题';break
        case "checkbox": type = '多选题';break
        case "score": type = '评分题'; break
      }
      return type
    },
    isShow(option) {
      let flag = false
      if(this.selections !== null)
      this.selections.forEach(selection => {
        if(selection.value === option.value) flag = true
      })
      this.selections2.forEach(selection => {
        if(selection.value === option.value) flag = true
      })
      return flag
    },
    addArgument2() {
      if(this.selections2.length >= 5){
        this.$message.error('最多只能添加五个因变量')
      } else this.selections2.push({value: ''})
    },
    deleteClick2() {
      this.selections2.pop()
    },
    printClick() {
      for(let i = 0; i < this.selections2.length; i++) {
        if(this.selections2[i].value !== '') {
          this.showGraph[i] = 'primary'
          this.print(i)
        } else this.showGraph[i] = ''

      }
    },
    print(index){
      console.log('这里是' + index);
      // 生成数据
      // 获得因变量和自变量 value是选择器的唯一标识
      // 获得x的questionId和type
      let x_id = 0, x_type = '', y_id = 0, y_type = ''
      if(this.selections.length === 1) {
        let value = this.selections[0].value
        for(let i = 0; i < this.questions.length; i++){
          if(this.questions[i].value === value){
            x_id = this.questions[i].questionId
            x_type = this.questions[i].type
          }
        }
      }

      // 获取y的questionId和type， 假设y只有一个的情况

      let value = this.selections2[index].value
      for(let i = 0; i < this.questions.length; i++){
        if(this.questions[i].value === value){
          y_id = this.questions[i].questionId
          y_type = this.questions[i].type
        }
      }

      // 调用接口
      const data = {
        questionnaireId: Number(this.$route.query.questionnaireId),
        questionId_x: Number(x_id),
        questionType_x: x_type,
        questionId_y: Number(y_id),
        questionType_y: y_type
      }
      let amount = 0, rawData = []
      axios.post('/api/questionnaire/cross', data).then((res) => {
        if(res.data.code === 0) {
          console.log(res);
          amount = res.data.data.amount_y
          rawData = res.data.data.arr
          console.log(rawData);
          //处理数据
          let legendData = [], xAxisData = [], seriesData = []
          //legendData
          legendData = this.questions
              .find(question => question.questionId === y_id).options
              .map(option => option.text)
          console.log(legendData);

          //xAxisData
          xAxisData = this.questions
              .find(question => question.questionId === x_id).options
              .map(option => option.text)
          console.log(xAxisData);

          //seriesData
          let i = 0
          legendData.forEach(y => {
            let buf = {}
            buf.name = y
            buf.type = 'line'
            buf.label = {
              show: true,
              position: 'top',
              formatter: function (params){
                return params.value + '%'
              }
            }
            let data_y = []
            for(let j = 0; j < legendData.length; j++){
              data_y.push(amount===0 ? 0 : rawData[i][j] / amount * 100)
            }
            buf.data = data_y
            i++
            seriesData.push(buf)
          })
          console.log(seriesData);
          this.$nextTick(() => {
            this.picDraw(legendData, xAxisData, seriesData, index)
          })
        } else this.$message.error(res.data.msg)
      })

    },
    picDraw(legendData, xAxisData, seriesData, index) {
      let myChart = echarts.getInstanceByDom(document.getElementById(this.graph_id[index])); //有的话就获取已有echarts实例的DOM节点。
      if (myChart == null) { // 如果不存在，就进行初始化。
        myChart = echarts.init(document.getElementById(this.graph_id[index]));
      }
      // let myChart = echarts.init(document.getElementById(this.circleId))
      // let data = []
      // this.options.forEach(option => {
      //   data.push({name: option.text, value: option.optionAmount})
      // })

      let option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: legendData //因变量的
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            mark: {show: true},
            restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData //自变量的
        },
        yAxis: {
          type: 'value'
        },
        series: seriesData
      };
      myChart.setOption(option, true)
      window.onresize = function () {
        setTimeout(() => {
          myChart.resize()
        }, 500)
      }
    }
  }
}
</script>

<style scoped>
.main {
  margin-left: 18%;
}
.argument {
  vertical-align: top;
  /*background-color: salmon;*/
  width: 50%;
  display: inline-block;
}
.dependency {
  vertical-align: top;
  /*background-color: cadetblue;*/
  width: 50%;
  display: inline-block;
}
.title {
  font-size: 20px;
  font-weight: bold;
  /*color: steelblue;*/
}
.graph {
  height: 600px;
  width: 80%;
  margin-top: 40px;
}
.descriptionNumber {
  font-size: 22px;
  color: #666666;
}
.descriptionTitle {
  font-size: 18px;
}
.descriptionType {
  color: silver;
}
.card {
  border-color: rgba(64, 158, 243, 0.5);
  width: 80%;
}
.head {
  font-weight: bold;
  font-size: 30px;
}
</style>